
<template>
  <div class="form-container">
    <!-- <div style="display:flex;"> -->
      <h2>{{ isEdit ? '编辑视频' : '新增视频' }}</h2>

      <el-button style="margin-bottom:20px"  v-if="isEdit" @click="routerAfterClassQuestions">课后习题管理</el-button>
    <!-- </div> -->

    <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入标题" />
      </el-form-item>

      <el-form-item label="视频文件" prop="url">
        <el-upload
          :headers="uploadHeaders"
          class="upload-demo"
          drag
          :auto-upload="true"
          action="/dev-api/ossUpload/uploadVideo"
          :on-progress="handleVideoProgress"
          :on-success="handleVideoSuccess"
          :before-upload="beforeVideoUpload"
          :on-remove="clearVideo"
          :file-list="videoFileList"
          accept=".mp4">
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">拖拽视频到此处或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip">只能上传mp4文件，且不超过500MB</div>
            <el-progress v-if="videoProgress > 0" :percentage="videoProgress" />
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item label="排序号" prop="sort">
        <el-input-number v-model="formData.sort" :min="1" />
      </el-form-item>

      <el-form-item label="时长(秒)" prop="duration">
        <el-input-number v-model="formData.duration" :min="1" />
      </el-form-item>

      <el-form-item label="是否免费" prop="isFree">
        <el-radio-group v-model="formData.isFree">
          <el-radio label="0">免费</el-radio>
          <el-radio label="1">收费</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="观看次数" prop="viewCount">
        <el-input-number v-model="formData.viewCount" :min="0" />
      </el-form-item>

      <el-form-item>
        <el-button type="danger" @click="handleDelete" v-if="isEdit">删除</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getToken } from '@/utils/auth';
import { defineExpose } from 'vue';
import { useRouter } from 'vue-router';
const router = useRouter();
const props = defineProps({
  formData: Object,
  isEdit: Boolean
})

const emit = defineEmits(['submit', 'cancel', 'delete', 'update:formDatas'])

// 本地状态管理
const localFormData = ref({ ...props.formData })
const formRef = ref()
const uploadHeaders = ref({
  'Authorization': `Bearer ` + getToken(),
})
const imageProgress = ref(0)
const videoProgress = ref(0)
const coverFileList = ref([])

// 修复1：直接管理视频文件列表状态
const videoFileList = ref([])

// 修复2：仅在初始化时设置文件列表
onMounted(() => {

  if (props.isEdit && props.formData.url) {
    videoFileList.value = [{
      name: '当前视频',
      url: props.formData.url
    }]
  }
})

const routerAfterClassQuestions = () => {
  console.log(props.formData)
  // emit('routerAfterClassQuestions', props.formData)
  router.push({
    path: 'afterClassQuestions',
    query: {
      courseId: props.formData.courseId,
      categoryId: props.formData.categoryId,
      videoId: props.formData.id
    }
  })
}
// 移除对formData的watch监听

const rules = reactive({
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序号', trigger: 'blur' }],
  duration: [{ required: true, message: '请输入时长', trigger: 'blur' }]
})


const beforeVideoUpload = (file) => {
  const isVideo = file.type === 'video/mp4'
  const isLt500M = file.size / 1024 / 1024 < 500
  if (!isVideo) {
    ElMessage.error('只能上传MP4格式的视频!')
    return false
  }
  if (!isLt500M) {
    ElMessage.error('视频大小不能超过500MB!')
    return false
  }
  return true
}

const handleVideoProgress = (event) => {
  videoProgress.value = Math.round((event.loaded / event.total) * 100)
}

// 修复3：直接更新文件列表状态
const handleVideoSuccess = (response, file) => {
  console.log("上传 成功")
  videoProgress.value = 0
  // 更新文件列表
  videoFileList.value = [{
    name: file.name,
    url: response.data
  }]

  // 更新表单数据
  console.log("props.formData",props.formData)
  emit('update:formDatas', {
    ...props.formData,
    url: response.data
  })
}

const clearVideo = () => {
  videoFileList.value = []
  videoProgress.value = 0
  // formData.value.url = ''
  emit('update:formDatas', {
    ...props.formData,
    url: ""
  })
}
defineExpose({
  clearVideo
});
const handleSubmit = () => {
  // console.log('handleSubmit',localFormData)
  formRef.value.validate((valid) => {
    if (valid) {
      // console.log(props.formData)
      // 使用本地状态提交
      emit('submit', props.formData)
    }
  })
}

const handleCancel = () => {
  emit('cancel')
}

const handleDelete = () => {
  emit('delete', props.formData.id)
}
</script>
<style scoped>
.form-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}
.upload-demo {
  width: 100%;
}
</style>
